# coding: utf8
__author__ = 'Tony'

import logging


logger = logging.getLogger('err')


def urlopen(req, timeout=5, specify_proxy=None, password=None, username=None):
	"""
	请求url
	:param req: <Request>
	:param timeout: 超时时间
	:param specify_proxy: (host, port) 指定代理
	:return: 响应对象
	"""
	import urllib2

	if specify_proxy:
		proxy = specify_proxy
		auth_handler = urllib2.HTTPBasicAuthHandler()
		auth_handler.add_password(None, 'http://%s' % req.get_host(), password, username)
		proxy_handler = urllib2.ProxyHandler({'http': '%s:%s' % proxy})
		opener = urllib2.build_opener(proxy_handler, auth_handler)
		return opener.open(req, timeout=timeout)
	else:
		return urllib2.urlopen(req, timeout=timeout)


def urlopen_with_location(url, data=None, location=None, headers=None, timeout=5, method='GET'):
	"""
	使用指定地区的代理请求数据
	:param url: <str>
	:param data: <str>
	:param location: <int: 地区代码>
	:param headers: <dict: http头部参数>
	:param timeout: <int: 超时时间>
	:return: <str: content>
	"""
	import httplib2
	import socks
	import config

	proxy = config.proxy_list.get(location)

	if proxy:
		host, port, passwd, username = proxy
		h = httplib2.Http(
			proxy_info=httplib2.ProxyInfo(
				socks.PROXY_TYPE_HTTP,
				host, port,
				proxy_pass=passwd,
				proxy_user=username
			),
			timeout=timeout,
		)
	else:
		h = httplib2.Http(timeout=timeout)

	if method == 'POST':
		if headers:
			headers['Content-Type'] = 'application/x-www-form-urlencoded'
		else:
			headers = {'Content-Type': 'application/x-www-form-urlencoded'}

	try:
		res, content = h.request(url, method, data, headers=headers)
	except Exception as ex:
		logger.exception('urlopen_with_location: %s @ %s' % (ex, proxy))
		raise ex

	return content

